package a66weding.com.jiehuntong;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import a66weding.com.jiehuntong.activity.PopGoodsActivity;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.PushBean;
import a66weding.com.jiehuntong.beans.VersionBean;
import a66weding.com.jiehuntong.common.CommonHandler;
import a66weding.com.jiehuntong.common.UpdateAppController;
import a66weding.com.jiehuntong.common.UpdateConstants;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.http.NetStatusUtil;
import a66weding.com.jiehuntong.pager.BasePager;
import a66weding.com.jiehuntong.pager.CateguryPager;
import a66weding.com.jiehuntong.pager.DiyPager;
import a66weding.com.jiehuntong.pager.HomePager;
import a66weding.com.jiehuntong.pager.MinePager;
import a66weding.com.jiehuntong.pager.ToolsPager;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private RadioGroup mRadioGroup;
    private RadioButton rb_home;
    private RadioButton rb_categury;
    private RadioButton rb_diy;
    private RadioButton rb_tool;
    private RadioButton rb_mine;
    private ViewPager mMainPager;
    private static int mPosition;
    private MyHandler mHandler;
    private static ArrayList<BasePager> mPagers;
    private static final int WHAT_EXIT_FLAG = 0x127;
    private boolean mExitFlag;
    private List<OnBackListener> listeners = new ArrayList<OnBackListener>();
    private HomeBaseFragment mFragment;
    public static int getResultCode = 5;
    public static int getResultForCartCode = 6;
    public static int getResultForHomecity = 7;
    public static int getResultForMeCode = 4;
    private int returnPageIndex;
    private String cityName = "北京";
    private PopupWindow mAreaPop;
    public static boolean isNewVersion;
    private VersionBean mVersionBean;
    private static final int UPDATEVERSION = 12;
    private static final int PERMISSION_REQUEST = 20;
    public boolean isQuGuangguang;
    public int mHomeCurrentItem;
    private boolean mustUpDate = false;
    private Intent intent;
    private Context context;
    private PushBean pushBean;
    public static boolean isFirstIntoHome = true;
    public static boolean isFirstIntoCategury = true;
    public static boolean isFirstIntoDiy = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        isFirstIntoHome = true;
        isFirstIntoCategury = true;
        isFirstIntoDiy = true;
        ((GlobalApplication) getApplication()).getActivityManager().addActivity("MainActivity", this);
        ((GlobalApplication) getApplication()).getMainActivityManager().addActivity("MainActivity", this);  //MainActivity自己的管理类
        isNewVersion = ((GlobalApplication) getApplication()).isDownNewVersion();
        intent = getIntent();
        if (intent != null) {
            returnPageIndex = intent.getIntExtra("index", 1);
        }
        initview();
        initData();
        mHandler.sendEmptyMessageDelayed(UPDATEVERSION, 5000);
        requestPermission();
        pushBean = (PushBean) intent.getSerializableExtra("pushBean");
        if (pushBean != null) {
            startPushActivity();
        }
    }

    private void initview() {
        rb_home = (RadioButton) findViewById(R.id.rb_home);
        rb_categury = (RadioButton) findViewById(R.id.rb_categury);
        rb_diy = (RadioButton) findViewById(R.id.rb_diy);
        rb_tool = (RadioButton) findViewById(R.id.rb_tool);
        rb_mine = (RadioButton) findViewById(R.id.rb_mine);
        mRadioGroup = (RadioGroup) findViewById(R.id.rgroup_content);
        mMainPager = (ViewPager) findViewById(R.id.main_viewpager);
    }

    public void initData() {
        mHandler = new MyHandler(this);
        mPagers = new ArrayList<>();
        mPagers.add(new HomePager(this));
        mPagers.add(new CateguryPager(this));
        mPagers.add(new DiyPager(this));
        mPagers.add(new ToolsPager(this));
        mPagers.add(new MinePager(this));
        mRadioGroup.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
        if (returnPageIndex != 0) {
            switch (returnPageIndex) {
                case 1:
                    rb_home.setChecked(true);
                    break;
                case 2:
                    rb_categury.setChecked(true);
                    break;
                case 3:
                    rb_diy.setChecked(true);
                    break;
                case 4:
                    rb_tool.setChecked(true);
                    break;
                case 5:
                    rb_mine.setChecked(true);
                    break;
            }
        } else {
            rb_home.setChecked(true); // 默认选中主页
        }
    }

    /**
     * 6.0申请权限
     */
    public void requestPermission() {
        boolean camera = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED;
        boolean sdCard = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED;
        boolean phone = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED;
        if (camera || sdCard || phone) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CALL_PHONE}, PERMISSION_REQUEST);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }

    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST) {
            if (grantResults.length < 1) {
                CUtils.showToast("拒绝某些权限可能会造成程序异常崩溃，给您使用带来不便");
            }
        }
    }

    /**
     * 自定义 OnCheckedChangeListener
     * 点击按钮切换到相应的页面
     */
    class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                default: // R.id.rb_index 首页
                    mPosition = 0;
                    break;
                case R.id.rb_categury: // 分类
                    mPosition = 1;
                    break;
                case R.id.rb_diy: // 结婚
                    mPosition = 2;
                    break;
                case R.id.rb_tool: // 工具
                    mPosition = 3;
                    break;
                case R.id.rb_mine: // 我
                    mPosition = 4;
                    break;
            }
            setFragment();
        }
    }

    /**
     * 设置 Fragment 到布局中
     */
    public void setFragment() {
        HomePager mHomePager = (HomePager) mPagers.get(0);
        mHomePager.getMhandler().removeCallbacksAndMessages(null);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        mFragment = new HomeBaseFragment();
        transaction.replace(R.id.flay_frag, mFragment);
        transaction.commit();
    }

    public static class HomeBaseFragment extends Fragment {
        public HomeBaseFragment() {
        }

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                                 @Nullable Bundle savedInstanceState) {
            BasePager pager = getBasePager();
            if (null != pager)
                return pager.mRootView;
            return null;
        }
    }

    /**
     * 根据索引位置获取指定的 BasePager 页面
     */
    public static BasePager getBasePager() {
        BasePager pager = mPagers.get(mPosition);
        if (null != pager) {
            pager.mInit = true;
            if (mPosition == 0) {//首页
                HomePager mHomePager = (HomePager) mPagers.get(mPosition);
                if (isFirstIntoHome) {
                    mHomePager.setPageIndex(1);
                    pager.initData();
                    isFirstIntoHome = false;
                }
                //轮播广告条
                mHomePager.getMhandler().sendEmptyMessageDelayed(HomePager.TOPVIEWSCROLL, 4000);
            } else if (mPosition == 1) {//分类
                if (isFirstIntoCategury) {
                    pager.initData();
                    isFirstIntoCategury = false;
                } else {
                    pager.notifyData();
                }
            } else if (mPosition == 2) {//结婚
                if (isFirstIntoDiy) {
                    pager.initData();
                    isFirstIntoDiy = false;
                } else {
                    pager.notifyData();
                }
            } else {//我的
                pager.initData();
            }
        }
        return pager;
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        outState.putInt("position", mPosition);
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (returnPageIndex == 1 && isQuGuangguang) {
            initData();
        }
        if (mPosition == 0) {
            HomePager mHomePager = (HomePager) mPagers.get(0);
            mHomePager.getMhandler().sendEmptyMessageDelayed(HomePager.TOPVIEWSCROLL, 4000);
        }
        MobclickAgent.onResume(this);
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        pushBean = (PushBean) intent.getSerializableExtra("pushBean");
        if (pushBean != null) {
            startPushActivity();
        }
    }

    private void startPushActivity() {
        Intent intent = new Intent(context, PopGoodsActivity.class);
        intent.putExtra("pushBean", pushBean);
        context.startActivity(intent);
    }

    @Override
    protected void onPause() {
        HomePager mHomePager = (HomePager) mPagers.get(0);
        mHomePager.getMhandler().removeCallbacksAndMessages(null);
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        if (mAreaPop != null && mAreaPop.isShowing()) {
            mAreaPop.dismiss();
        }
        HomePager mHomePager = (HomePager) mPagers.get(0);
        mHomePager.getMhandler().removeCallbacksAndMessages(null);
        //为了安全起见先调用所有的destroyPager后再销毁上下文
        for (BasePager basePager : mPagers) {
            basePager.destroyPager();
        }
        //销毁pager用的Activity的上下文
        for (BasePager basePager : mPagers) {
            basePager.mActivity = null;
        }
        super.onDestroy();
    }

    /**
     * 再按一次退出
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
                if (0 != mPosition) {
                    rb_home.setChecked(true);
                } else if (!mExitFlag) {
                    if (((GlobalApplication) getApplication()).isLogin){//不是吃瓜群众
                        CUtils.showToast(R.string.dblclick_to_exit);
                        mExitFlag = true;
                        mHandler.sendEmptyMessageDelayed(WHAT_EXIT_FLAG, 2000);
                        }else {//吃瓜群众就关闭页面
                        finish();
                    }
                } else if (mExitFlag) {
                    ((GlobalApplication) getApplication()).getActivityManager().exitApp();
                }
                return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    /**
     * 自定义 Handler, 用于实现按两次退出
     */
    class MyHandler extends CommonHandler<MainActivity> {
        public MyHandler(MainActivity activity) {
            super(activity);
        }

        @Override
        protected void handle(MainActivity activity, Message msg) {
            switch (msg.what) {
                case WHAT_EXIT_FLAG:
                    if (null != activity) {
                        activity.mExitFlag = false;
                    }
                    break;
                case UPDATEVERSION:
                    if (null != activity && mRadioGroup.isShown()) {
                        if (isNewVersion) {
                            mVersionBean = DataWareHourse.getInstance().getVersionBean();
                            showOrderPopupWindowNew(mVersionBean);
                        }
                    }
                    break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        notifydata();
        if (mPosition == 2) {
            isFirstIntoDiy = true;
        }
        if (requestCode == getResultCode) {
            notifydata();
        }
        if (requestCode == getResultForCartCode) {
            returnPageIndex = 1;
            if (data != null) {
                boolean isChange = data.getBooleanExtra("isChange", false);
                if (isChange) {
                    returnPageIndex = 1;
                    initData();
                } else {
                    return;
                }
            }
        }
        if (requestCode == getResultForMeCode) {
            mPosition = 4;
            notifydata();
        }
        if (requestCode == 10) {
            notifydata();
        }
        if (requestCode == 1) {
            notifydata();
        }
        if (requestCode == getResultForHomecity) {
            mPosition = 0;
            if (data != null) {
                String city = data.getStringExtra("city");
                cityName = city;
            }
            getBasePager().notifyData();
        }
        //通知pager的
        getBasePager().onActivityResult(requestCode, resultCode, data);
    }

    public void notifydata() {
        getBasePager();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_tv:
                UpdateAppController.stopUpdateService(this);
                if (mAreaPop != null) {
                    mAreaPop.dismiss();
                    mAreaPop = null;
                }
                if (mustUpDate) {
                    finish();
                }
                break;
            case R.id.update_btn:
                //让服务去更新
                if (isNewVersion && mVersionBean != null) {
                    boolean iswifi = NetStatusUtil.isWifi(MainActivity.this);
                    boolean is4g = NetStatusUtil.is4G(MainActivity.this);
                    if (mAreaPop != null) {
                        mAreaPop.dismiss();
                        if (mustUpDate) {
                            finish();
                        }
                    }
                    if (iswifi || is4g) {
                        Toast.makeText(getApplication(), "开始下载...", Toast.LENGTH_LONG).show();
                        UpdateAppController.startUpdateServiceForDown(this, UpdateConstants.ACTIVITY_FLAG, true, mVersionBean);
                    } else {
                        showDialog();
                    }
                }
                break;
        }
    }

    /**
     * 新版版本更新UI
     *
     * @param versionBean
     */
    public void showOrderPopupWindowNew(VersionBean versionBean) {
        //填充更新弹窗UI以及找到对应的控件
        View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.new_dialog_update, null);
        TextView closeTv = (TextView) contentView.findViewById(R.id.close_tv);
        Button updateBtn = (Button) contentView.findViewById(R.id.update_btn);
        TextView versionTv = (TextView) contentView.findViewById(R.id.showversion_tv);
        //创建弹窗并设置
        mAreaPop = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        mAreaPop.setContentView(contentView);
        mAreaPop.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.whitetranslucenthalf2)));
        mAreaPop.setOutsideTouchable(false);//外部不让触摸
        if (versionBean != null) {
            mustUpDate = versionBean.getData().getB_forcibly();
            if (mustUpDate) {//判断是否强制更新,如果强制更新点击弹窗外无效并且只能更新或者退出应用
                closeTv.setText("退出");
                mAreaPop.setFocusable(false);//当强制更新的时候失去焦点,关闭页面
            } else {
                mAreaPop.setFocusable(true);//非强制更新获得焦点可以点击返回键关闭弹窗
            }
            versionTv.setText("定的V" + versionBean.getData().getNew_versionName() + "版本,敬请体验。    ");
            /*更新日志内容 String update_log = versionBean.getData().getUpdate_log();
            if (update_log.contains("\\r")) {
                update_log = update_log.replaceAll("\\\\r", "\r\n");
            }*/
        }
        mAreaPop.showAtLocation(mMainPager, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        //设置各个控件的点击响应
        closeTv.setOnClickListener(MainActivity.this);
        updateBtn.setOnClickListener(MainActivity.this);
    }

    /**
     * 这是提醒用户非WIFI下载的提醒
     */
    private void showDialog() {
        AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setMessage("检测到您的网络处于非wifi状态或非4g状态,下载新版本将消耗一定的流量,是否继续下载?");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UpdateAppController.startUpdateServiceForDown(MainActivity.this, UpdateConstants.ACTIVITY_FLAG, true, mVersionBean);
                dialog.dismiss();
            }
        });
        builder.show();
    }

    public ViewPager getViewpager() {
        return (ViewPager) findViewById(R.id.main_viewpager);
    }

    public interface OnBackListener {
        void onBack();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode && event.getRepeatCount() == 0) {
            if (mustUpDate) {
                mExitFlag = true;
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 监听我们的回退建
     */
    @Override
    public void onBackPressed() {
        if (mustUpDate) {
            finish();
        } else {
            if (listeners.size() == 0) {
                //把我们当前的activity退到后台 但不是finish
                moveTaskToBack(true);
            } else {
                for (OnBackListener listener : listeners) {
                    listener.onBack();
                }
            }
        }
    }

    public void setmHomeCurrentItem(int mHomeCurrentItem) {
        this.mHomeCurrentItem = mHomeCurrentItem;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public static void setIsNewVersion(boolean isNewVersion) {
        MainActivity.isNewVersion = isNewVersion;
    }
}
